<template>
    <div class="categories_wrap">
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 内容主体区域 -->
        <el-card>
            <!-- 添加分类按钮 -->
            <el-button @click="showAddClassForm" type="primary">添加分类</el-button>
            <!-- 分类列表 -->
            <tree-table :expand-type="false" show-index border :selection-type="false" :data="goodsCategoriesList" :columns="goodsCategoriesColumns">
                <!-- 是否有效 -->
                <template slot="isok" slot-scope="scope">
                    <i v-if="scope.row.cat_deleted" class="el-icon-error"></i>
                    <i v-else class="el-icon-success"></i>
                </template>
                <!-- 排序 -->
                <template slot="sort" slot-scope="scope">
                    <el-tag v-if="scope.row.cat_level == 0">一级</el-tag>
                    <el-tag v-else-if="scope.row.cat_level == 1" type="success">二级</el-tag>
                    <el-tag v-else type="info">三级</el-tag>
                </template>
                <!-- 操作 -->
                <template slot="set" slot-scope="scope">
                    <el-row>
                        <el-col :span="12">
                            <el-button @click="showModifyClassForm(scope.row)" size="small" type="primary" icon="el-icon-edit">编辑</el-button>
                        </el-col>
                        <el-col :span="12">
                            <el-button @click="removeClass(scope.row.cat_id)" size="small" type="danger" icon="el-icon-delete">删除</el-button>
                        </el-col>
                    </el-row>
                </template>
            </tree-table>
            <!-- 分页区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="goodsCategoriesParams.pagenum"
            :page-sizes="[5, 10, 15, 20]" :page-size="goodsCategoriesParams.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>

        <!-- 添加分类对话框 -->
        <el-dialog @close="clearActiveClassValue" title="提示" :visible.sync="isShowAddClassForm" width="50%">
            <!-- 添加分类名称 -->
            <el-form :model="addClassForm" :rules="addClassFormRules" ref="addClassFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="分类名称" prop="cat_name">
                    <el-input v-model="addClassForm.cat_name"></el-input>
                </el-form-item>
                <el-form-item label="选择分类">
                     <!-- 级联选择器 -->
                    <el-cascader :key="cascaderKey" class="selectClass" v-model="activeClassValue" :options="goodsCategoriesList" :props="addClassProps" @change="handleChange"></el-cascader>
                </el-form-item>
            </el-form>
           
            <span slot="footer" class="dialog-footer">
                <el-button @click="isShowAddClassForm = false">取 消</el-button>
                <el-button type="primary" @click="submitAddClassForm">确 定</el-button>
            </span>
        </el-dialog>


        <!-- 编辑分类对话框 -->
        <el-dialog @close="clearActiveClassValue" title="提示" :visible.sync="isShowModifyForm" width="50%">
            <!-- 添加分类名称 -->
            <el-form :model="addClassForm" :rules="addClassFormRules" ref="addClassFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="分类名称" prop="cat_name">
                    <el-input v-model="addClassForm.cat_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="isShowModifyForm = false">取 消</el-button>
                <el-button type="primary" @click="submitModifyClassForm">确 定</el-button>
            </span>
        </el-dialog>




    </div>
</template>

<script>
export default {
    data() {
        return {
            // 存储商品分类列表
            goodsCategoriesList: [],
            // 获取商品分类列表的参数
            goodsCategoriesParams: {
                type: '',
                pagenum: 1,
                pagesize: 5
            },
            // 分类总条数
            total: 0,
            // 表格配置
            goodsCategoriesColumns: [
                { label: '分类名称', prop: 'cat_name'},
                { label: '是否有效', type: 'template', template: 'isok'},
                { label: '排序', type: 'template', template: 'sort' },
                { label: '操作', type: 'template', template: 'set' },

            ],
            // 显示或隐藏添加分类对话框
            isShowAddClassForm: false,
            // 选中的分类绑定值
            activeClassValue: [],
            // 添加分类的配置
            addClassProps: {
                expandTrigger: 'hover',
                label: 'cat_name',
                value: 'cat_id',
                checkStrictly: true,
            },
            // 添加分类名称的表单参数
            addClassForm: {
                cat_name: ''
            },
            // 添加分类名称的验证规则
            addClassFormRules: {
                cat_name: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ]
            },
            // 服务器添加分类表单的参数
            serverAddClassParams: {
                cat_pid: 0,
                cat_level: 0
            },
            // 解决级联bug
            cascaderKey: 0,
            // 显示与隐藏编辑表单
            isShowModifyForm: false,
            // 被编辑的分类ID
            modifyClassID: 0,
        }
    },
    mounted() {
        this.getGoodsCategoriesList();
    },
    methods: {
        // 获取商品分类列表
        async getGoodsCategoriesList() {
            const { data: res } = await this.$http.get('categories', { params: this.goodsCategoriesParams });
            if (res.meta.status != 200) return this.$message.error('获取商品分类列表失败');
            this.goodsCategoriesList = res.data.result;
            this.total = res.data.total;
            ++this.cascaderKey;
        },
        // 获取改变后每页显示的条数
        handleSizeChange(newSize) {
            this.goodsCategoriesParams.pagesize = newSize;
            this.getGoodsCategoriesList();
        },
        // 获取改变后的当前页码
        handleCurrentChange(newPageNum) {
            this.goodsCategoriesParams.pagenum = newPageNum;
            this.getGoodsCategoriesList();
        },
        // 显示添加分类对话框
        showAddClassForm() {
            this.isShowAddClassForm = true;
        },
        // 当添加分类的分类选项被选择时触发
        handleChange() {
            // 说明是一级分类，重置为0
             
            if (this.activeClassValue.length != 3) {
                this.serverAddClassParams.cat_pid = this.activeClassValue[0];;
                this.serverAddClassParams.cat_level = 0;
            } else {
                this.serverAddClassParams.cat_pid = this.activeClassValue[1];
                this.serverAddClassParams.cat_level = this.activeClassValue[2];;
            }
            
        },
        // 提交添加分类表单
        submitAddClassForm() {
            this.$refs.addClassFormRef.validate(async valid => {
                if (valid) {
                    const { data: res } = await this.$http.post('categories', {
                        cat_pid: this.serverAddClassParams.cat_pid,
                        cat_name: this.addClassForm.cat_name,
                        cat_level: this.serverAddClassParams.cat_level
                    });
                    console.log(res);
                    if (res.meta.status != 201) return this.$message.error('创建分类失败');
                    this.$message.success('创建分类成功');
                    this.isShowAddClassForm = false;
                    this.getGoodsCategoriesList();
                } else {
                    this.$message.error('数据验证错误');
                }
            })
        },
        // 添加分类表单关闭的时候，清空级联已选择的分类数组
        clearActiveClassValue() {
            this.activeClassValue = [];
            this.addClassForm.cat_name = '';
        },
        // 显示编辑分类
        showModifyClassForm(classCate) {
            this.isShowModifyForm = true;
            this.modifyClassID = classCate.cat_id
        },
        // 提交编辑表单
        async submitModifyClassForm() {
            const { data: res } = await this.$http.put(`categories/${this.modifyClassID}`, this.addClassForm);
            if (res.meta.status != 200) return this.$message.error('修改失败');
            this.$message.success('修改成功');
            this.getGoodsCategoriesList();
            this.isShowModifyForm = false;
        },
        // 删除分类
        removeClass(classID) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete(`categories/${classID}`);
                if (res.meta.status != 200) return this.$message.error('删除失败');
                this.$message.success('删除成功');
                this.getGoodsCategoriesList();
            }).catch(() => {
                this.$message.info('取消了删除');
            });
            
        }

    }
}
</script>

<style lang="less" scoped>
.selectClass {
    width: 100%;
}
</style>